/**
 * Created by Forcs on 16/4/8.
 */

var fs = require('fs');
var moment = require('moment')
var LogManager = function (options) {

  var _self = this
  _self._options = {}
  _self._recordDate = moment('1970-07-01', 'YYYY-MM-DD');
  _self._logFiles = {};

  _self.defs = {
    expired: 7 * 24 * 3600
  };

  _self._initOptions = function (options) {
    ['logPath', 'expired']
      .forEach(function (item) {
        if (options[item]) {
          _self._options[item] = options[item];
        } else if (_self.defs[item]) {
          _self._options[item] = _self.defs[item];
        }
      });
  };

  _self._resetLogFiles = function () {
    _self._logFiles.app = [];
    _self._logFiles.page = [];
    _self._logFiles.content = [];
    _self._logFiles.event = [];
    _self._logFiles.order = [];
  };

  _self._initOptions(options);
  _self._resetLogFiles();
};

LogManager.prototype.onLogging = function () {
  var _self = this;
  var now = moment();
  var pre = _self._recordDate;
  if (now.year() === pre.year()
    && now.month() === pre.month()
    && now.date() === pre.date()) {
    // 同一天,不用检查log文件的更新
    return;
  } else {
    _self._recordDate = now;
  }
  var root = _self._options.logPath;
  var logFiles = fs.readdirSync(root);
  if (logFiles) {
    _self._resetLogFiles();
    logFiles.forEach(function (item) {
      if (item.indexOf('app') > 0) {
        _self._logFiles.app.push(item);
      } else if (item.indexOf('page') > 0) {
        _self._logFiles.page.push(item);
      } else if (item.indexOf('content') > 0) {
        _self._logFiles.content.push(item);
      } else if (item.indexOf('event') > 0) {
        _self._logFiles.event.push(item);
      } else if (item.indexOf('order') > 0) {
        _self._logFiles.order.push(item);
      }
    })
  }
};

LogManager.prototype.logFilesFrom = function (timestamps) {
  var format = 'YYYY-MM-DD';
  var _self = this;
  var all = _self._logFiles;
  var res = {};
  for (var key in timestamps) {
    var d = moment(moment(timestamps[key], 'X').format(format), format);
    var files = all[key];
    res[key] = [];
    if (!files) {
      continue;
    }
    files.forEach(function (item) {
      var name = item.split('.')[0];
      var args = name.split('_');
      var date = moment(args[2], format);
      var path = _self._options.logPath + '/' + item;
      if (date.diff(d) > 0 && fs.existsSync(path)) {
        res[key].push(path);
      }
    })
  }
  return res;
};

LogManager.prototype.clearExpiredLogs = function (type) {
  this.removeLogFilesFromToday(type, this._options.expired);
};

LogManager.prototype.removeLogFilesFromToday = function (type, before) {
  this.removeLogFilesFrom(type, moment().format('YYYY-MM-DD'), before);
};

LogManager.prototype.removeLogFilesFrom = function (type, when, before) {
  var _self = this;
  var all = _self._logFiles;
  var res = {};
  var w = moment(when, 'YYYY-MM-DD');
  for (var key in all) {
    if (key === type) {
      var files = all[key];
      if (!files) {
        break;
      }
      
      res[key] = [];
      files.forEach(function (item) {
        var name = item.split('.')[0];
        var args = name.split('_');
        var date = moment(args[2], 'YYYY-MM-DD');
        var filePath = _self._options.logPath + '/' + item;
        if (date.diff(w) < (-1) * before * 1000 && fs.existsSync(filePath)) {
          fs.unlinkSync(filePath);
        }
      });

      break;
    }
  }
  return res;
};

LogManager.prototype.getLog = function (logLine) {
  var content = this.format(logLine);
  if (content === null) {
    return null;
  }
  if (arguments.length > 1) {
    var options = arguments[1];
    var lastTime = 0;
    if (options.timestamp) {
      lastTime = moment(options.timestamp, 'X');
    }
    if (content.datetime.diff(lastTime) < 0) {
      return null;
    }
  }
  content.timestamp = parseInt(content.datetime.format('X'));
  content.datetime = content.datetime.format('YYYY-MM-DD HH:mm:ss.SSS');
  return content;
};

LogManager.prototype.format = function (logString) {
  var re = /(\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}\]) (\[\w+\]) (app|page|content|event|order) - (\{.*\})/gi;
  var matchs = re.exec(logString);
  var res = {
    datetime: moment(),
    content: {},
    type: ''
  };
  if (matchs) {
    res.datetime = moment(matchs[1], 'YYYY-MM-DD HH:mm:ss.SSS');
    res.content = JSON.parse(matchs[4]);
    res.type = matchs[3];
  } else {
    res = null;
  }
  return res;
};

module.exports = LogManager;